import 'package:flutter/material.dart';
import 'package:flutter_bilibili/navigator/hi_navigator.dart';
import 'package:flutter_bilibili/page/favorite_page.dart';
import 'package:flutter_bilibili/page/home_page.dart';
import 'package:flutter_bilibili/page/profile_page.dart';
import 'package:flutter_bilibili/page/ranking_page.dart';
import 'package:flutter_bilibili/util/color.dart';

class BottomNavigator extends StatefulWidget {
  @override
  _BottomNavigatorState createState() => _BottomNavigatorState();
}

class _BottomNavigatorState extends State<BottomNavigator> {
  final _defaultColor = Colors.grey;  //  默认颜色
  final _activeColor = primary;       //  激活颜色
  int _currentIndex = 0;              //  当前下标
  static int initialPage = 0;         //  初始化下标
  final PageController _controller = PageController(initialPage: initialPage);  //  实例化PageController
  List<Widget> _pages;  //  存放PageView页面
  bool _hasBuild = false;

  @override
  Widget build(BuildContext context) {
    _pages = [HomePage(onJumpTo: (index)=>_onJumpTo(index,pageChange: false),), RankingPage(), FavoritePage(), ProfilePage()];
    if (!_hasBuild) {
      //  页面第一次打开时通知打开的是哪个tab
       HiNavigator.getInstance()
          .onBottomTabChange(initialPage, _pages[initialPage]);
      _hasBuild = true; 
    }
    return Scaffold(
      body: PageView(
        controller: _controller,
        children: _pages,
        onPageChanged: (index) => _onJumpTo(index, pageChange: true),   //  页面改变时触发
        physics: NeverScrollableScrollPhysics(),  //  禁止滚动
      ),
      bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentIndex,
          onTap: (index) => _onJumpTo(index),
          type: BottomNavigationBarType.fixed,
          selectedItemColor: _activeColor,
          items: [
            _bottomItem('首页', Icons.home, 0),
            _bottomItem('排行', Icons.local_fire_department, 1),
            _bottomItem('收藏', Icons.favorite, 2),
            _bottomItem('我的', Icons.live_tv, 3),
          ]),
    );
  }

  //  底部tab构造方法
  _bottomItem(String title, IconData icon, int index) {
    return BottomNavigationBarItem(
        icon: Icon(icon, color: _defaultColor),
        activeIcon: Icon(icon, color: _activeColor),
        label: title);
  }

  //  跳转至与当前下标相对应的页面
  void _onJumpTo(int index, {pageChange = false}) {
    if (!pageChange) {
      //  让PageView展示对应tab
      _controller.jumpToPage(index);
    } else {
      HiNavigator.getInstance().onBottomTabChange(index, _pages[index]);
    }
    setState(() {
      _currentIndex = index;
    });
  }
}
